package org.springblade.modules.pay.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.R;
import org.springblade.modules.order.entity.Order;
import org.springblade.modules.order.entity.OrderRefund;
import org.springblade.modules.pay.service.WxPayService;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 微信支付 控制器
 *
 * @author Blade
 * @since 2024-09-02
 */
@RestController
@AllArgsConstructor
@RequestMapping("/WxPay")
@Slf4j
public class WxPayController {
	private final WxPayService wxPayService;


	/**
	 * 生成uuid
	 *
	 * @return {@link R }
	 */
	@GetMapping("generateUuid")
	public R generateUuid(){
		return R.data(getOrderNum());
	}
	/**
	 * 创建订单
	 *
	 * @param order 订单
	 * @return {@link R }
	 */
	@PostMapping("createOrder")
	public R createOrder(@RequestBody @Valid Order order){
		return R.data(wxPayService.createOrder(order));
	}


	/**
	 * 付款回调
	 *
	 * @param request 请求
	 * @return {@link R }
	 */
	@PostMapping("payNotify")
	public R payNotify(HttpServletRequest request){
		try {
			return R.data(wxPayService.payNotify(request));
		} catch (Exception e) {
			throw new ServiceException(e.getMessage());
		}
	}



	/**
	 * 退款
	 *
	 * @param orderRefund  退款
	 * @return {@link R }
	 */
	@PostMapping("refund")
	public R refund(@RequestBody  OrderRefund orderRefund){
		try {
			return R.data(wxPayService.refund(orderRefund));
		} catch (Exception e) {
			throw new ServiceException(e.getMessage());
		}
	}


	/**
	 * 退款回调
	 *
	 * @param request 请求
	 * @return {@link R }
	 */
	@PostMapping("refundNotify")
	public R refundNotify(HttpServletRequest request){
		try {
			return R.data(wxPayService.refundNotify(request));
		} catch (Exception e) {
			throw new ServiceException(e.getMessage());
		}
	}
	/**
	 * 生成订单号（20位）：时间（精确到毫秒）+3位随机数
	 */
	public static synchronized  String getOrderNum() {
		//时间（精确到毫秒）
		DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
		String localDate = LocalDateTime.now().format(ofPattern);
		//3位随机数
		String randomNumeric = RandomStringUtils.randomNumeric(3);
		String orderNum = localDate + randomNumeric;
		log.info("订单号:{}", orderNum);
		return orderNum;
	}
}
